package com.threeonemeeting.activity;

import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.snda.lib.http.HttpUtil;
import com.snda.lib.http.ICallBack;
import com.snda.lib.http.TaskManager;
import com.snda.lib.ui.MessageBox;
import com.snda.lib.util.MiscHelper;
import com.snda.lib.util.TimeHelper;
import com.threeonemeeting.Const;
import com.threeonemeeting.DataCenter;
import com.threeonemeeting.R;
import com.threeonemeeting.adapter.RelativeMeetingListAdapter;
import com.threeonemeeting.db.AppDBHelper;
import com.threeonemeeting.listview.CornerListView;
import com.threeonemeeting.model.FullMeetingInfo;
import com.threeonemeeting.model.RelativeMeetingListItemInfo;
import com.threeonemeeting.tab.BaseTabActivity;
import com.threeonemeeting.tab.MultiActivityTab;
import com.threeonemeeting.task.GetMeetingInfoTask;
import com.threeonemeeting.task.GetMeetingMoreDetailTask;
import com.threeonemeeting.task.HttpConst;
import com.threeonemeeting.util.MiscUtil;

// 会议的详细资料页面
public class MeetingDetailActivity extends BaseTabActivity implements
		ICallBack, OnItemClickListener {

	private PopupWindow mPopupWindow = null;
	private ProgressDialog mProcessDialog = null;

	private int nMeetingId = 0;

	private RelativeMeetingListAdapter mAdapter;
	private CornerListView relativeList = null;

	@Override
	protected void onStop() {
		super.onStop();

		if (mPopupWindow != null) {
			mPopupWindow.dismiss();
		}
	}

	private void initMeeting(final FullMeetingInfo fullInfo) {

		// 初始化界面中的各个元素
		TextView meetingTitle = (TextView) findViewById(R.id.meeting_title);
		meetingTitle.setText(fullInfo.strTitle);

		// 时间
		TextView meetingTime = (TextView) findViewById(R.id.meeting_time);
		String strTime = MiscUtil.getBetweenTime(fullInfo.strBeingTime,
				fullInfo.strEndTime);
		meetingTime.setText(strTime);

		// 收费会议还是免费会议
		TextView meetingType = (TextView) findViewById(R.id.meeting_type);
		meetingType.setText(fullInfo.lPrice > 0 ? "收费会议" : "免费会议");

		// 会议类型，研讨会还是展会
		TextView meetingCategory = (TextView) findViewById(R.id.meeting_category);
		meetingCategory.setText(fullInfo.strEventTypeName);

		// 会议地址
		TextView meetingAddress = (TextView) findViewById(R.id.meeting_address);
		meetingAddress.setText(fullInfo.strAddress);

		// 会议描述
		TextView meetingDesc = (TextView) findViewById(R.id.meeting_desc);
		String strDesc = MiscUtil
				.splitAndFilterString(fullInfo.strSummary, 200);
		meetingDesc.setText(strDesc);

		// 会议图片
		ImageView imageView = (ImageView) findViewById(R.id.meeting_image);
		String strThumbUrl = Const.URL.BASE_THUMB_URL;
		if (fullInfo.strLogoUrl != null
				&& fullInfo.strLogoUrl.equalsIgnoreCase("") == false) {
			strThumbUrl += URLEncoder.encode(fullInfo.strLogoUrl);
			MiscUtil.setImageView(imageView, strThumbUrl);
		} else {
			imageView.setBackgroundResource(R.drawable.default_meeting_image);
		}

		// 资料按钮禁用
		Button btnInfo = (Button) findViewById(R.id.btn_info);
		btnInfo.setOnClickListener(null);
		// btnInfo.setTextColor(R.color.light3gray);

		// 评论按钮
		Button btnComment = (Button) findViewById(R.id.btn_comment);
		btnComment.setOnClickListener(null);

		// 报名
		Button btnEnroll = (Button) findViewById(R.id.btn_enroll);
		btnEnroll.setOnClickListener(null);

		// 分享
		Button btnShare = (Button) findViewById(R.id.btn_share);
		btnShare.setOnClickListener(btnShareClickListener);

		// 展开按钮
		Button btnExpand = (Button) findViewById(R.id.btn_expand);
		btnExpand.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				RelativeLayout expandLayout = (RelativeLayout) findViewById(R.id.layout_expand);
				expandLayout.setVisibility(View.GONE);

				TextView meetingDesc = (TextView) findViewById(R.id.meeting_desc);
				meetingDesc.setText(Html.fromHtml(fullInfo.strSummary));
			}

		});

		mAdapter = new RelativeMeetingListAdapter(this);
		relativeList = (CornerListView) findViewById(R.id.relativeList);
		relativeList.setAdapter(mAdapter);
		relativeList.setOnItemClickListener(this);
	}

	private void initMeetingDetail(final FullMeetingInfo fInfo) {
		Boolean bDocuments = fInfo.nDocuments == 0 ? false : true;
		Boolean bCloseTopic = fInfo.bCloseTopic;
		Boolean bCloseJoin = fInfo.bCloseJoin;
		Boolean bIsJoined = fInfo.bIsJoined;

		// 已经过期
		String strLimitTime = fInfo.strJoinLimitTime;
		if (strLimitTime != null) {
			strLimitTime = strLimitTime.replace('T', ' ');
		}
		Date limitTime = TimeHelper.stringToDate(strLimitTime,
				"yyyy-MM-dd HH:mm:ss");
		if (bCloseJoin == false && limitTime != null) {
			if (System.currentTimeMillis() - limitTime.getTime() > 0) {
				bCloseJoin = true;
			}
		}

		mAdapter.clear();

		// 相关会议
		List<Integer> listRelative = fInfo.listRelativeMeeting;
		int nSize = listRelative.size();
		for (int i = 0; i < nSize; i++) {

			Integer meetingId = listRelative.get(i);
			if (meetingId == null)
				continue;

			FullMeetingInfo fullInfo = DataCenter.getInstance().listFullMeeting
					.getFullMeetingInfo(meetingId);
			if (fullInfo == null)
				continue;

			RelativeMeetingListItemInfo info = new RelativeMeetingListItemInfo();
			info.nMeetingId = meetingId;
			info.strMeetingName = fullInfo.strTitle;
			mAdapter.add(info);
		}

		// MiscUtil.setListViewHeight(relativeList);
		mAdapter.notifyDataSetChanged();

		ScrollView sv = (ScrollView) findViewById(R.id.scroll_view);
		sv.scrollTo(0, 0);

		LinearLayout listLayout = (LinearLayout) findViewById(R.id.layout_list);
		LayoutParams lp = listLayout.getLayoutParams();
		lp.height = mAdapter.getCount() * MiscUtil.dp2px(42);
		listLayout.setLayoutParams(lp);

		// 资料按钮禁用
		Button btnInfo = (Button) findViewById(R.id.btn_info);
		if (bDocuments == null || bDocuments == false) {
			btnInfo.setOnClickListener(null);
		} else {
			btnInfo.setTextColor(0xFF000000);
			btnInfo.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					Bundle b = new Bundle();
					b.putInt("id", nMeetingId);
					startActivity("MeetingDataListActivity", b);
				}

			});
		}

		// 评论按钮
		Button btnComment = (Button) findViewById(R.id.btn_comment);
		if (btnComment != null) {
			if (bCloseTopic == true) {
				btnComment.setOnClickListener(null);
			} else {
				btnComment.setTextColor(0xFF000000);
				btnComment.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {

						Bundle b = new Bundle();
						b.putInt("id", nMeetingId);
						startActivity("MeetingCommentsListActivity", b);
					}

				});
			}
		}

		// 报名
		Button btnEnroll = (Button) findViewById(R.id.btn_enroll);
		if (btnEnroll != null) {
			if (bCloseJoin == true) {
				btnEnroll.setOnClickListener(null);
				btnEnroll.setText("报名结束");
			}
			// 如果已经报名过
			else if (bIsJoined == true) {
				btnEnroll.setTextColor(0xFF000000);
				btnEnroll.setOnClickListener(null);
				btnEnroll.setText("已经报名");
			} else {
				btnEnroll.setTextColor(0xFF000000);
				btnEnroll.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						Bundle b = new Bundle();
						b.putInt("eid", nMeetingId);
						startActivity("EnrollMeetingActivity", b);
					}
				});
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_meeting_detail);
		init("会议明细");

		nMeetingId = getIntent().getExtras().getInt("id");

		final FullMeetingInfo fullInfo = DataCenter.getInstance().listFullMeeting
				.getFullMeetingInfo(nMeetingId);
		if (fullInfo == null) {
			GetMeetingInfoTask task = new GetMeetingInfoTask(this, this);
			Bundle params = new Bundle();
			params.putString("eid", String.valueOf(nMeetingId));
			TaskManager.addTask(task, params, false);

			MultiActivityTab parent = (MultiActivityTab) this.getParent();
			mProcessDialog = MessageBox.showProcessDlg(parent, "正在读取会议详情");
			return;
		}

		initMeeting(fullInfo);

		// 请求关于会议的额外补充信息
		GetMeetingMoreDetailTask task = new GetMeetingMoreDetailTask(this, this);
		task.nMeetingId = nMeetingId;
		Bundle params = new Bundle();
		params.putString("eid", String.valueOf(nMeetingId));
		params.putString(
				"uid",
				String.valueOf(DataCenter.getInstance().currentLoginUserInfo.nUserId));
		params.putString("pass",
				DataCenter.getInstance().currentLoginUserInfo.strPassword);
		TaskManager.addTask(task, params, true);

		AppDBHelper db = DataCenter.getInstance().getDB();
		db.updateMeetingVisitTime(nMeetingId, System.currentTimeMillis());
	}

	@Override
	public void back() {

		if (mPopupWindow != null) {
			if (mPopupWindow.isShowing() == true) {
				mPopupWindow.dismiss();
				return;
			}
		}

		super.back();
	}

	OnClickListener btnShareClickListener = new OnClickListener() {
		public void onClick(View v) {

			if (mPopupWindow == null || mPopupWindow.isShowing() == false) {
				LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
				View shareView = mLayoutInflater.inflate(
						R.layout.lib_select_share_way, null);
				mPopupWindow = new PopupWindow(shareView,
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				mPopupWindow.showAtLocation(findViewById(R.id.btn_share),
						Gravity.CENTER, 0, 0);

				Button btnShareToSinaWeibo = (Button) shareView
						.findViewById(R.id.btnShareFromSinaWeibo);
				Button btnShareToQQWeibo = (Button) shareView
						.findViewById(R.id.btnShareFromQQWeibo);
				Button btnShareToEmail = (Button) shareView
						.findViewById(R.id.btnShareFromEmail);
				Button btnShareToSMS = (Button) shareView
						.findViewById(R.id.btnShareFromSMS);
				Button btnShareToOther = (Button) shareView
						.findViewById(R.id.btnShareFromOther);

				Button btnClose = (Button) shareView
						.findViewById(R.id.btnClose);

				btnShareToSinaWeibo.setOnClickListener(shareToSinaWeibo);
				btnShareToQQWeibo.setOnClickListener(shareToQQWeibo);
				btnShareToEmail.setOnClickListener(shareToEmail);
				btnShareToSMS.setOnClickListener(shareToSMS);
				btnShareToOther.setOnClickListener(shareToOther);

				btnClose.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						if (mPopupWindow != null) {
							mPopupWindow.dismiss();
						}
					}

				});
			}
		}
	};

	// 分享到新浪微博
	final OnClickListener shareToSinaWeibo = new OnClickListener() {

		public void onClick(View v) {
			mPopupWindow.dismiss();

			// 检查是否关联了新浪微博帐号
			String strSinaWeibo = MiscUtil.getPrefer("SinaWeiboToken");
			if (MiscHelper.isEmpty(strSinaWeibo) == true) {
				MessageBox.showToast(MeetingDetailActivity.this,
						"您尚未绑定新浪微博帐号，\n请先在\"更多-微博绑定\"中进行绑定");
				return;
			}

			FullMeetingInfo fullInfo = DataCenter.getInstance().listFullMeeting
					.getFullMeetingInfo(nMeetingId);
			if (fullInfo == null)
				return;

			Bundle b = new Bundle();
			b.putString("to", "sina");
			b.putString("title", fullInfo.strTitle);
			b.putString("url", "http://www.31huiyi.com/event/" + fullInfo.nId
					+ "/");
			startActivity("ShareMeetingActivity", b);
		}
	};

	// 分享到腾讯微博
	final OnClickListener shareToQQWeibo = new OnClickListener() {

		public void onClick(View v) {
			mPopupWindow.dismiss();

			// 检查是否关联了新浪微博帐号
			String strQQWeibo = MiscUtil.getPrefer("QQWeiboToken");
			if (MiscHelper.isEmpty(strQQWeibo) == true) {
				MessageBox.showToast(MeetingDetailActivity.this,
						"您尚未绑定腾讯微博帐号，请先在\"更多-微博绑定\"中进行绑定");
				return;
			}

			FullMeetingInfo fullInfo = DataCenter.getInstance().listFullMeeting
					.getFullMeetingInfo(nMeetingId);
			if (fullInfo == null)
				return;

			Bundle b = new Bundle();
			b.putString("to", "qq");
			b.putString("title", fullInfo.strTitle);
			b.putString("url", "http://www.31huiyi.com/event/" + fullInfo.nId
					+ "/");
			startActivity("ShareMeetingActivity", b);
		}
	};

	// 分享到邮件
	final OnClickListener shareToEmail = new OnClickListener() {

		public void onClick(View v) {
			mPopupWindow.dismiss();

			final FullMeetingInfo fullInfo = DataCenter.getInstance().listFullMeeting
					.getFullMeetingInfo(nMeetingId);
			if (fullInfo == null)
				return;

			// 帐号编辑框
			String strUrl = "http://www.31huiyi.com/event/" + fullInfo.nId
					+ "/";
			String strContent = "我在31会议网发现一个有用的会议，" + fullInfo.strTitle + "，"
					+ strUrl + "，推荐给您。 ";

			try {
				Intent intent = new Intent(Intent.ACTION_SEND);
				intent.putExtra("subject", "我在31会议网发现一个有用的会议"); //
				intent.putExtra("body", strContent); // 正文
				startActivity(intent); // 调用系统的mail客户端进行发送
			} catch (ActivityNotFoundException e) {
				MessageBox
						.showToast(MeetingDetailActivity.this, "没有找到合适的邮件客户端");
			}
		}
	};

	// 分享到SMS
	final OnClickListener shareToSMS = new OnClickListener() {

		public void onClick(View v) {
			mPopupWindow.dismiss();

			final FullMeetingInfo fullInfo = DataCenter.getInstance().listFullMeeting
					.getFullMeetingInfo(nMeetingId);
			if (fullInfo == null)
				return;

			// 帐号编辑框
			String strUrl = "http://www.31huiyi.com/event/" + fullInfo.nId
					+ "/";
			String strContent = "我在31会议网发现一个有用的会议，" + fullInfo.strTitle + "，"
					+ strUrl + "，推荐给大家";

			Uri smsToUri = Uri.parse("smsto://123456");
			Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
			sendIntent.putExtra("sms_body", strContent);
			sendIntent.setType("vnd.android-dir/mms-sms");
			startActivity(sendIntent);
		}
	};

	// 分享到SMS
	final OnClickListener shareToOther = new OnClickListener() {

		public void onClick(View v) {
			mPopupWindow.dismiss();

			final FullMeetingInfo fullInfo = DataCenter.getInstance().listFullMeeting
					.getFullMeetingInfo(nMeetingId);
			if (fullInfo == null)
				return;

			// 帐号编辑框
			String strUrl = "http://www.31huiyi.com/event/" + fullInfo.nId
					+ "/";
			String strContent = "我在31会议网发现一个有用的会议，" + fullInfo.strTitle + "，"
					+ strUrl + "，推荐给大家";

			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");
			intent.putExtra(Intent.EXTRA_SUBJECT, "31会议分享");
			intent.putExtra(Intent.EXTRA_TEXT, strContent);
			startActivity(Intent.createChooser(intent, getTitle()));
		}
	};

	public void doCallBack(Map<String, Object> mapData) {
		Integer msgType = (Integer) mapData.get(HttpConst.KEY_TASK_TYPE);
		if (msgType == null) {
			Log.d(Const.Tag, "can't find type in response type");
			return;
		}

		if (msgType == HttpConst.TASKTYPE_GETMEETINGINFO) {
			mProcessDialog.dismiss();
		}

		Integer nError = (Integer) mapData.get(HttpUtil.KEY_ERROR_CODE);
		if (nError == null || nError != HttpUtil.ERROR_SUCCESS) {
			Log.d(Const.Tag, "response return error:" + nError + " type:"
					+ msgType);
			return;
		}

		if (msgType == HttpConst.TASKTYPE_MOREMEETINGDETAIL) {
			// 获取热门的会议列表
			FullMeetingInfo fInfo = DataCenter.getInstance().listFullMeeting
					.getFullMeetingInfo(nMeetingId);
			if (fInfo == null)
				return;

			initMeetingDetail(fInfo);
		} else if (msgType == HttpConst.TASKTYPE_GETMEETINGINFO) {
			FullMeetingInfo fInfo = (FullMeetingInfo) mapData.get("detail");
			if (fInfo != null) {
				initMeeting(fInfo);
				initMeetingDetail(fInfo);
			}
		}
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		int nIndex = arg2;

		RelativeMeetingListItemInfo nameInfo = mAdapter.getItem(nIndex);
		if (nameInfo == null)
			return;

		Bundle b = new Bundle();
		b.putInt("id", nameInfo.nMeetingId);
		startActivity(MeetingDetailActivity.this.strFromActivity,
				"MeetingDetailActivity", b);
	}
}
